import serial
import serial.tools.list_ports
import time
import threading


def CheckPorts ():	##check useable commports on your computer
	port_list = list(serial.tools.list_ports.comports())
	PortName = []
	if len (port_list) <= 0:
		print ("Cannot find a Serial Port!")
	else:
		for i in range (0, len(port_list)):
			PortName.append(port_list[i])

	return port_list, PortName

def PortInitial(CommNumber):	## Initialize you CommPort
	CommPort = serial.Serial(
                port = CommNumber,
                baudrate = 9600,
                bytesize = 8,
                parity = 'N',
                stopbits = 1, 
                timeout = 50, 
                xonxoff = 0, 
                rtscts = 0)
	return CommPort

##定义用于从串口接收数据的线程
def Receiving(threadName, delay = 0.050):
	while true :
		data = CommPort.readline()
		time.sleep(delay)

class myThread(threading.Thread):
	def __init__(self, threadID, name, delay):
		self.threadID = threadID
		self.name = name
		self.delay = delay

	def runThread(self):
		print ("开始线程：" + self.name)
		Receiving(self.name, self.delay)



if __name__ == '__main__':
	
	Portlist = []
	PortName = []
	CommNumber = ''

	(Portlist, PortName) = CheckPorts()

	print("本机可用COMPort有：")
	for i , element in enumerate(PortName):
		print(PortName[i])

	CommNumber = input("请输入端口号（例：COM1）：")

	CommPort = PortInitial(CommNumber)

	if CommPort.isOpen():
		print(""" '%s' is open. """ %CommNumber)

	else:
		CommPort.open()

##添加多循环接收串口数据的线程
	thread_Receiving = myThread(1, Receiving, 0.05)
	thread_Receiving.start()

	for i in range (0, 10):
		CommPort.write(b"hello")
		time.sleep(0.1)
		print(data)

	print ("输入结束")
	time.sleep(3)
	CommPort.close()



	



